<?php

/**
 * Class QReply.php
 *
 * Class responsible for storing the responses of comments to the questions at the stage of question Discussion
 *
 * @author Jose Oliveira <jafo@ua.pt> 2012
 */

class QReply{

	private $reply;
	private $dateHour;
	private $qCommnetID;
	private $userID;

	/**
	 * 
	 * @param string $reply
	 * @param integer $qCommentID
	 * @param integer $userID
	 */
	function __construct($reply, $qCommentID, $userID){

		if(isset($reply) && isset($qCommentID) && isset($userID)){
			$this->reply=$reply;
			$this->qCommnetID=$qCommentID;
			$this->userID=$userID;
			$this->dateHour=date("Y-m-d H:i:s");
		}

	}


	/**
	 * Method that stores a new response to a certain comment
	 * @throws Exception
	 * @return bool
	 */
	public function storeReply(){

		if($this->reply != ""){
				
			$conn=new ConnDBUser();
			$conn->connect();

			$reply=mysql_real_escape_string($this->reply);

			$result=mysql_query("insert into qReply(reply, dateHour, qCommentID, userID) values('$reply',
			'" . $this->dateHour . "', '" . $this->qCommnetID . "', '" . $this->userID . "')");

			if(!$result){
				throw new Exception( "Lamentamos mas ocorreu um erro: " . mysql_error());
			}

			try{
				$conn->disconnect($result);
				return true;
			}catch(Exception $e){
				$e->getMessage();
			}
		}
	}
	
	/**
	 * Method that returns all replies made to a comment
	 * @param integer $commentID
	 * @throws Exception
	 * @return array
	 */
	public function getReplies($commentID){
		
		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select * from qReply where qCommentID='$commentID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$info=array();
			while($registo=mysql_fetch_array($result)){
					
				$name=$this->getUserName($registo['userID']);

				$temp=array('qReplyID' => $registo['qReplyID'], 'reply' => $registo['reply'], 'dateHour' => $registo['dateHour'],
				'qCommentID' => $registo['qCommentID'], 'author' => $name);

				array_push($info, $temp);
			}

			$conn->disconnect($result);
			return $info;

		}catch(Exception $e){
			$e->getMessage();
		}
	}
	
	
	/**
	 * Method that receives an userID and returns the respective username 
	 * @param integer $userID
	 * @throws Exception
	 * @return string
	 */
	private function getUserName($userID){

		$conn=new ConnDBUser();
		$conn->connect();

		$result=mysql_query("select name from user where userID='$userID'");

		if(!$result){
			throw new Exception("Lamentamos mas ocorreu um erro");
		}

		try{

			$registo=mysql_fetch_array($result);

			$conn->disconnect($result);
			return $registo['name'];

		}catch(Exception $e){
			print $e->getMessage();
		}

	}


}



?>